<?php
/**
 * 获取设备状态接口
 *
 * 
 */

use Workerman\Protocols\Http;
use Workerman\Worker;
use Workerman\Mysql;

 class mod_poster_information_management_details{

    public function entry($param){

        return $this->do_mod_poster_information_management_details($param);
    }


    /**
    * do_mod_poster_information_management_details
    * 获取批次等级分布
    *
    * @access private
    * @param $param batch
    * @since 1.0
    * @return array(errcode,errmsg,rtv)
    */
    private function do_mod_poster_information_management_details($param){
        $action = $_POST["action"];
        //var_dump($action);
        //获取海报校稿数

        // 返回结果示例
        // {
        //     1: [{       第几次校稿
        //         page: 1,   页
        //         area: 1,   区
        //         picture_id: 7,   图片
        //         picture_path: "/2020/03/02/1_1583079056.jpg",
        //         department_arr: [{    绑定部门
        //             department_id: 1,
        //             department_name: "市场部",
        //             contents: "xxx"
        //         }]
        //     }],
        //     2: [{
        //         picture_id: 7,
        //         page: 1,
        //         area: 1,
        //         picture_path: "/2020/03/02/1_1583079056.jpg",
        //         department_arr: [{
        //             department_id: 1,
        //             department_name: "市场部",
        //             contents: "xxx"
        //         }]
        //     }]
        // }

        // 获取总共有几次校稿
        // [{poster_contents_id:1,poster_number:1},{poster_contents_id:2,poster_number:2}]
        if($action == "set_poster_contents"){

            $param = $_POST['param'];
            $submission = @$param["submission"];

            if(!empty($param["user_id"])){
                $user_id = $param["user_id"];
            }else{
                $userObj= Token::getToken($_SERVER['HTTP_ACCESS_TOKEN']);
                $user_id = $userObj[0]['id'];
            }

            $content = $param["content"];

            $sql = "SELECT c.id as department_id,c.department_headquarters_id,b.class FROM hf_mes_user a 
				INNER JOIN hf_mes_groups b ON a.groups=b.id 
				INNER JOIN hf_mes_department c ON a.department=c.id
				WHERE a.id='$user_id'";
            $dp = sql_query($sql);
            $department_id = $dp[0]["department_id"];
            $department_headquarters_id = $dp[0]["department_headquarters_id"];
            $group = $dp[0]["class"];
            // group为1、2、3,分别代表采购员、副总监、总监
            if($submission == 1){
                // 部门点击提交稿件按钮
                $poster_contents_id = $param["poster_contents_id"];

                $sql_str = " AND c.id='$user_id'";
                if($group == "副总监"){
                    $sql_str = " AND c.id='$user_id'";
                }elseif($group == "总监"){
                    $sql_str = " AND b.department_id IN (SELECT id FROM hf_mes_department WHERE department_headquarters_id='$department_headquarters_id')";
                }

                // 查看该部门下所有稿件是否校稿  原来上一位程序员就这样写 看不懂重构吧
                $sql = "SELECT b.id,b.contents,d.name,e.name as department_name FROM hf_mes_poster_picture a 
					INNER JOIN hf_mes_poster_picture_department b ON a.id = b.picture_id 
					INNER JOIN hf_mes_poster_contents f ON a.poster_contents_id = f.id 
					INNER JOIN hf_mes_user c ON b.department_id=c.department
					INNER JOIN hf_mes_poster_management d ON f.poster_id=d.id
					INNER JOIN hf_mes_department e ON b.department_id=e.id
					WHERE a.poster_contents_id= $poster_contents_id $sql_str";
                $ret = sql_query($sql);
                if(count($ret) <= 0){
                    return array("errcode"=>4002, "errmsg"=>"获取部门稿件失败", "rtval"=>"");
                }
                $finish = 1;
                $sql_str =  "";
                foreach($ret as $values){
                    //var_dump($values);die;
                    if($values["contents"] == Null || $values["contents"] == "" || count(json_decode($values["contents"])) == 0){
                        $errmsg = '';
                        $finish = 0;
                        $errmsg .= $values['department_name'].'-'.$values['name'].';';
                    }
                    $sql_str .= $values["id"].",";
                }
                //var_dump($ret);die;
                $sql_str = rtrim($sql_str,",");
                if($finish == 0){
                    return array("errcode"=>4002, "errmsg"=>'还有部门没完成校稿:'.$errmsg, "rtval"=>"");
                }


                $sql = "update hf_mes_poster_picture_department set finish=1,finish_date='".date("Y-m-d H:i:s")."' WHERE id in ($sql_str)  AND finish=0";

                if($group == "副总监"){
                    $sql = "update hf_mes_poster_picture_department set deputy_director='$user_id' WHERE id in ($sql_str)";
                }elseif($group == "总监"){
                    $sql = "update hf_mes_poster_picture_department set chief_inspector='$user_id' WHERE id in ($sql_str)";
                }
                $rt = sql_query($sql);
                $this->update_history_contents($group,$sql_str);
                $this->send_email($group,$poster_contents_id,$department_id,$department_headquarters_id);
            }elseif ($submission == 3){


                // 单张海报点击保存按钮
                $picture_department_id = $param["picture_department_id"];
                $contents = $param["contents"];

                $sql_str  ="contents='$contents'";

                $sql = "update hf_mes_poster_picture_department set $sql_str  WHERE id='$picture_department_id'";
                $rt = sql_query($sql);


            }else{
                // var_dump($param);
                // 单张海报点击保存按钮
                $picture_department_id = $param["picture_department_id"];
                $picture_id = $param["picture_id"];
                $contents = json_encode($param["contents"],JSON_UNESCAPED_UNICODE);

                //$contents_confirm = json_encode($param["contents_confirm"],JSON_UNESCAPED_UNICODE);
                // 如果用户角色是采购员和副总监，则保存历史数据
                //$sql_str  ="user_id='$user_id',contents='$contents',contents_confirm='$contents_confirm'";
                $sql_str  ="user_id='$user_id',contents='$contents'";
                if($group != "总监"){

                    if($group == "副总监"){
                        $sql_str.= ",deputy_director_contents='$contents'";
                    }else{
                        $sql_str.= ",user_contents='$contents'";
                    }
                }
                $sql = "update hf_mes_poster_picture_department set $sql_str  WHERE id='$picture_department_id'";
                $rt = sql_query($sql);

            }

            //return array("errcode"=> 0,"errmsg"=>"","rtval"=>$obj);
            $obj = '保存成功';

        }

        if($action == "get_poster_number"){
            $poster_id = $_POST["poster_id"];
            $sql = "SELECT id AS poster_contents_id,number FROM hf_mes_poster_contents WHERE poster_id='$poster_id'";
            $dp=sql_query($sql);
            $rt_obj = [];
            foreach($dp as $values){
                $o = new stdClass();
                $o->poster_contents_id = $values["poster_contents_id"];
                $o->number = $values["number"];
                array_push($rt_obj, $o);
            }
            $obj = new stdClass();
            $obj-> data = $rt_obj;
        }

        // 获取当次校稿下总共页数多少
        // {page_number:[1,2]}
        if($action  == "get_page_number_by_poster"){
            $poster_contents_id = $_POST["poster_contents_id"];
            $sql = "SELECT page FROM hf_mes_poster_picture WHERE poster_contents_id='$poster_contents_id' GROUP BY page";
            $dp=sql_query($sql);
            $ret = [];
            foreach($dp as $val){
                array_push($ret, $val["page"]);
            }
            sort($ret);
            $obj = new stdClass();
            $obj-> page_number = $ret;
        }

        // 通过当次校稿和当前页,获取绑定部门信息
        // [{department_id:1,name:"采购1部"},{department_id:2,name:"采购2部"}]
        if($action  == "get_department_id_by_poster_page"){
            $poster_contents_id = $_POST["poster_contents_id"];
            $page = $_POST["page"];
            $sql = "SELECT id FROM hf_mes_poster_picture WHERE poster_contents_id='$poster_contents_id' AND page='$page' LIMIT 1";
            $dp=sql_query($sql);
            $picture_id = $dp[0]["id"];
            $sql = "SELECT a.department_id,b.name FROM hf_mes_poster_picture_department a 
                    INNER JOIN hf_mes_department b ON a.department_id=b.id 
                    WHERE a.picture_id='$picture_id'";
            $dp=sql_query($sql);
            $ret = [];
            foreach($dp as $val){
                $obj = new stdClass();
                $obj->department_id = $val["department_id"];
                $obj->name = $val["name"];
                array_push($ret,$obj);
            }
            $obj = new stdClass();
            $obj-> department_arr = $ret;
        }

        // 通过当次校稿、当前页和当前部门，获取海报内容信息
        // [{area: 1,picture_department_id:1,picture_path:"/2020/03/02/1_1583079056.jpg",user_name:"",contents:"",,contents_confirm:""}]
        if($action  == "get_picture_list_by_poster_page_department"){
            $poster_contents_id = $_POST["poster_contents_id"];
            $page = $_POST["page"];
            $department_id = $_POST["department_id"];

            if(!empty($department_id)){
                $sql = "SELECT b.picture_path,c.id AS picture_department_id,IFNULL(d.name,c.user_id) as user_name,IFNULL(e.name,c.deputy_director) as deputy_director_name,IFNULL(f.name,c.chief_inspector) as chief_inspector_name,c.contents,c.contents_confirm FROM hf_mes_poster_contents a 
                    INNER JOIN hf_mes_poster_picture b ON a.id=b.poster_contents_id 
                    INNER JOIN hf_mes_poster_picture_department c ON b.id=c.picture_id 
                    LEFT JOIN hf_mes_user d ON d.id=c.user_id
                    LEFT JOIN hf_mes_user e ON e.id=c.deputy_director 
                    LEFT JOIN hf_mes_user f ON f.id=c.chief_inspector 
                    WHERE a.id='$poster_contents_id' AND  b.page='$page' 
                    AND c.department_id='$department_id'";

                $dp=sql_query($sql);

            }else{
                $sql = "SELECT b.picture_path,c.id AS picture_department_id,IFNULL(d.name,c.user_id) as user_name,IFNULL(e.name,c.deputy_director) as deputy_director_name,IFNULL(f.name,c.chief_inspector) as chief_inspector_name,c.contents,c.contents_confirm FROM hf_mes_poster_contents a 
                    INNER JOIN hf_mes_poster_picture b ON a.id=b.poster_contents_id 
                    INNER JOIN hf_mes_poster_picture_department c ON b.id=c.picture_id 
                    LEFT JOIN hf_mes_user d ON d.id=c.user_id
                    LEFT JOIN hf_mes_user e ON e.id=c.deputy_director 
                    LEFT JOIN hf_mes_user f ON f.id=c.chief_inspector 
                    WHERE a.id='$poster_contents_id' AND  b.page='$page'";

                $dp=sql_query($sql);
                //var_dump($dp);
                $data = [];

                $contents = [];
                if(count($dp) > 0){
                    foreach ($dp as $k=>$v){
                        $data[0] = $v;
                        if(!empty($v['contents'])){
                            $arr = json_decode($v['contents'],true);
                            foreach ($arr as $kk=>$vv){
                                array_push($contents,$vv);
                            }
                        }

                    }
                    //var_dump(json_encode($contents));die;
                    if(!empty($contents)){
                        $data[0]['contents'] = json_encode($contents);
                    }else{
                        $data[0]['contents'] = NULL;
                    }
                    //var_dump($data);
                    $dp = $data;
                }
            }

            $obj = $dp;

        }

        //获取导入button
        if($action  == "get_poster_button"){
            $poster_management_id = $_POST["poster_management_id"];
            $page = $_POST["page"]??1;
            $department_id = $_POST['department_id'];

            $sql = "SELECT id,poster_management_id,import_json,button_json
                    FROM hf_mes_poster_button_import
                    WHERE poster_management_id='$poster_management_id' AND page='$page'";

            //不传部门ID 查询总画布
            if(!empty($department_id)){
                $sql = $sql.' AND department_id='.$department_id;
            }

            //var_dump($sql);
            $dp=sql_query($sql);

            $data = [];
            if(!empty($dp)){
                foreach ($dp as $k=>$v){

                    $button_array = json_decode($v['button_json'],true);

                    $button_array['id'] = $v['id'];
                    $button_json[$k] = $button_array;

                    $Import_json[$k] = json_decode($v['import_json'],true);
                }
                $dp[0]['import_json'] = $Import_json;
                $dp[0]['button_json'] = $button_json;
                $data = $dp[0];
            }
            $obj = $data;

        }



        // 确认内容项
        // 把该内容确认加到contents_confirm中
        // 查询该次校稿所有海报是否确认完成，如果是，则把该次稿件finish置为1，提示该次稿件所有海报都校稿完成，可以进行下次校稿

        /**
         * do_set_poster_contents
         *
         *
         * @access private
         * @param $param
         * @since 1.0
         * @return array(errcode,errmsg,rtv)
         */
        if($action  == "get_button_csv"){
            //var_dump(111111);die;
            $poster_contents_id = $_POST["poster_contents_id"];
            $page = $_POST["page"];
            $department_id = $_POST["department_id"];

            if(!empty($department_id)){
                $sql = "SELECT b.picture_path,c.id AS picture_department_id,IFNULL(d.name,c.user_id) as user_name,IFNULL(e.name,c.deputy_director) as deputy_director_name,IFNULL(f.name,c.chief_inspector) as chief_inspector_name,c.contents,c.contents_confirm FROM hf_mes_poster_contents a 
                    INNER JOIN hf_mes_poster_picture b ON a.id=b.poster_contents_id 
                    INNER JOIN hf_mes_poster_picture_department c ON b.id=c.picture_id 
                    LEFT JOIN hf_mes_user d ON d.id=c.user_id
                    LEFT JOIN hf_mes_user e ON e.id=c.deputy_director 
                    LEFT JOIN hf_mes_user f ON f.id=c.chief_inspector 
                    WHERE a.id='$poster_contents_id' AND  b.page='$page' 
                    AND c.department_id='$department_id'";

                $dp=sql_query($sql);

                $dp[0]['contents'] = json_decode($dp[0]['contents']);

            }else{
                $sql = "SELECT b.picture_path,c.id AS picture_department_id,IFNULL(d.name,c.user_id) as user_name,IFNULL(e.name,c.deputy_director) as deputy_director_name,IFNULL(f.name,c.chief_inspector) as chief_inspector_name,c.contents,c.contents_confirm FROM hf_mes_poster_contents a 
                    INNER JOIN hf_mes_poster_picture b ON a.id=b.poster_contents_id 
                    INNER JOIN hf_mes_poster_picture_department c ON b.id=c.picture_id 
                    LEFT JOIN hf_mes_user d ON d.id=c.user_id
                    LEFT JOIN hf_mes_user e ON e.id=c.deputy_director 
                    LEFT JOIN hf_mes_user f ON f.id=c.chief_inspector 
                    WHERE a.id='$poster_contents_id' AND  b.page='$page'";

                $dp=sql_query($sql);
                //var_dump($dp);die;
                $data = [];

                $contents = [];
                if(count($dp) > 0){
                    foreach ($dp as $k=>$v){
                        $data[0] = $v;
                        if(!empty($v['contents'])){
                            $arr = json_decode($v['contents'],true);
                            foreach ($arr as $kk=>$vv){
                                array_push($contents,$vv);
                            }
                        }

                    }

                    if(!empty($contents)){
                        $data[0]['contents'] = $contents;
                    }else{
                        $data[0]['contents'] = [];
                    }
                    //var_dump($data);
                    $dp = $data;
                }
            }

            //var_dump($dp);die;
            if(!empty($dp)){
                foreach ($dp[0]['contents'] as $v){
                    //var_dump($v);die;
                    if(!empty($v->info)){
                        $info[]  = json_decode(json_encode($v->info),true);
                    }elseif(!empty($v['info'])){
                        $info[] = $v['info'];
                    }

                }

                // CSV对应的字段名
                $csv_val = array( 'sku', 'unit', 'price', 'name', 'desc', 'page', 'idx', 's_price', 'limit', 'area_time', 'mark', 'origin', 'flag','department_name');
               //var_dump($info);die;

                $url = $this->DownloadData('dc-'.time().'.csv',$csv_val,$info);
                //var_dump($url);
                $obj = $url;
            }else{
                return array("errcode"=>0, "errmsg"=>"", "rtval"=>"");
            }

        }


        if($action == "set_contents_confirm"){
            try{
                $picture_department_id = $_POST["picture_department_id"];

                $index = [];
                $contents_json = $_POST["contents"];
                $contents = json_decode($contents_json);
                foreach ($contents as $k=>$v){
                    if($v->is_confirm){
                        $index[] = $k;
                    }
                }

           /*     $open=fopen("log.txt","w" );
                fwrite($open,$contents_json);
                fclose($open);*/

                $sql = "SELECT b.poster_contents_id,a.contents_confirm FROM hf_mes_poster_picture_department a 
                        INNER JOIN hf_mes_poster_picture b ON a.picture_id = b.id
                        WHERE a.id='$picture_department_id' LIMIT 1";
                $dp=sql_query($sql);
                //$contents_confirm = json_decode($dp[0]["contents_confirm"]);

                //array_push($contents_confirm,$index);
                $sql = "UPDATE hf_mes_poster_picture_department SET contents_confirm='".json_encode($index)."',contents ='".$contents_json."'WHERE id='$picture_department_id' LIMIT 1";
                sql_query($sql);

                // 查询该次校稿所有海报是否确认完成
                $poster_contents_id = $dp[0]["poster_contents_id"];
                $sql = "SELECT b.contents,b.contents_confirm FROM hf_mes_poster_picture a 
                        INNER JOIN hf_mes_poster_picture_department b ON a.id = b.picture_id 
                        WHERE a.poster_contents_id='$poster_contents_id'";
                $dp=sql_query($sql);
                foreach($dp as $values){
                    if($values["contents"] == NULL || empty($values["contents"]) || count(json_decode($values["contents"])) != count(json_decode($values["contents_confirm"]))){
                        throw new Exception("done");
                    }
                }
                $sql = "UPDATE hf_mes_poster_contents SET finish=1 WHERE id='$poster_contents_id' LIMIT 1";
                sql_query($sql);
                $obj = "校稿内容已确认";
            }catch(Exception $e){
                return array("errcode"=> 0,"errmsg"=>"","rtval"=>$e->getMessage());
            }

        }
        
        return array("errcode"=> 0,"errmsg"=>"","rtval"=>$obj);
    }

     /**  如果大量数据导出 支持分页写入

      * [DownloadDate 公共导出csv]

      * @param  string                   $name   [文件名称]

      * @param  array                   $header [表头]

      * @param  array                    $data   [数据集]

      * @param                      $is_header   [真 假 是否取表头 解决循环写入问题]

      * @return array             name[文件名称]   filePath[文件路径]

      */

     public static function DownloadData($name='',$header=array(),$data=array(),$is_header=true){

         $Dir = G_CSV_DIR;
         $Dir2 = date("Y").'/'.date("m").'/'.date("d");
         $targetDir = $Dir.$Dir2;
         if (!file_exists($targetDir)) {
             $t = @mkdir($targetDir,0777,true);
         }

         $fileName = $name;

  //       set_time_limit(0);

//         ini_set('memory_limit','2048M');


         try {

             if (!$name || !$data) {

                 //throw new BadRequestHttpException('参数不可为空');
                 return false;
             }


             $header = implode(",",$header);

             $header = iconv('UTF-8', 'GBK//IGNORE', $header);

             $header = explode(",", $header);

             $fp = fopen($targetDir.$fileName, 'a+');

             if (!empty($header) && is_array($header) && $is_header) {

                 fputcsv($fp, $header);

             }

             //var_dump($data);die;
             foreach ($data as $row) {

                 $str = implode("@@@@",$row);
                 //var_dump($str);die;

                 $str = iconv('UTF-8', 'GBK//IGNORE', $str);

                 $str = str_replace(",","|",$str);

                 $row = explode("@@@@", $str);

                 fputcsv($fp, $row);

             }

             unset($data);

             if(ob_get_level()>0){

                 ob_flush();

             }

             flush();

            // ob_clean();
/*             Http::header("Content-type:text/csv;");
             Http::header("Content-Disposition:attachment;filename=" . $fileName);
             Http::header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
             Http::header('Expires:0');
             Http::header('Pragma:public');*/
             //ob_end_flush();
             return $data = [
                 'url' => '/'.$Dir2.$fileName,
                 'file_name' => $fileName,
             ];

         } catch (Exception $e) {
             return false;
             //throw new BadRequestHttpException($e->getMessage());//抛出异常

         }

     }

    /** 
    * create  
    * 通过 call_user_func 获得本class的实例
    * 
    * @access public 
    * @since 1.0 
    * @return object 本类的实例
    */  
    public static function create(){  
        static $instance;
        if (!$instance){  
            $instance = new mod_poster_information_management_details();  
        }
        return $instance;  
    }   
 }

?>